import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path:'/login', component: ()=> import('@/views/login/LoginPage.vue'),
    meta: { title: '登录页面' } },
    { 
      path:'/', 
      component: ()=> import('@/views/layout/LayoutContainer.vue'),
      redirect: '/article/manage',
      meta: { title: '文章管理' },
      children: [
        { // 文章管理
          path: '/article/manage', 
          component: ()=> import('@/views/article/ArticleMange.vue'),
          meta: { title: '文章管理' }
        },
        {// 文章频道
          path: '/article/channel', 
          component: ()=> import('@/views/article/ArticleChannel.vue'),
          meta: { title: '文章分类' }
        },
        // user 模块------------------------------------------------
        {// 用户头像
          path:'/user/avatar', 
          component: ()=> import('@/views/user/UserAvatar.vue'),
          meta: { title: '用户头像' }
        },
        {// 用户密码
          path:'/user/password', 
          component: ()=> import('@/views/user/UserPassword.vue'),
          meta: { title: '用户密码' }
        },
        {// 用户个人详情
          path:'/user/profile', 
          component: ()=> import('@/views/user/UserProfile.vue'),
          meta: { title: '个人详情' }
        },
      ]
  }
  ]
})

// 登录拦截，如果没有 token 就不可以访问别的页面
router.beforeEach((to) => {
  const userStore = useUserStore()
  if (!userStore.token && to.path !== '/login') return '/login'
})

router.beforeEach((to, from, next) => {
  document.title = to.meta.title || '默认标题';
  next();
});
export default router
